const Multer = require('koa-multer')
const path = require("path");
const Jimp = require('jimp');


const avatarUploader = new Multer({
  dest: './uploads/avatar'
})
const avatarHandler = avatarUploader.single('avatar')
const pictureUploader = new Multer({
  dest: './uploads/picture'
})
const pictureHandler = pictureUploader.array('picture', 9)

const pictureResize = async (ctx,next) => {
  const files = ctx.req.files
  for (const file of files) {
    const destPath = path.join(file.destination,file.filename)
    Jimp.read(file.path).then(image => {
      image.resize(1280,Jimp.AUTO).write(`${destPath}-large`)
      image.resize(640,Jimp.AUTO).write(`${destPath}-middle`)
      image.resize(320,Jimp.AUTO).write(`${destPath}-small`)
    })
  }
  await next()
}

module.exports = {avatarHandler, pictureHandler, pictureResize}